package com.angel.flieutils;

import com.angel.config.MyConfig;
import com.angel.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度ueditor富文本编辑器上传组件
 *
 * @author Rabit
 */
@RestController
@RequestMapping("/file")
public class UeditorUpload {
    @Autowired
    private MyConfig myConfig;

    @RequestMapping("/editorupload")
    @ResponseBody
    public Map<String, String> upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("upfile") MultipartFile file)
            throws Exception {
        Map<String, String> map = new HashMap<>();
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        if (file.isEmpty()) {
            map.put("state", "ERROR");
            return map;
        }
        String abPath = pathIsExists(myConfig.getFileuploadpath(), "cms");
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 这里我使用随机字符串来重新命名图片
        String tmppath = TimeUtils.getTime() + suffixName;
        fileName = abPath + File.separator + tmppath;
        // 这里的路径为Nginx的代理路径，这里是/data/images/xxx.png
        File dest = new File(fileName);
        //    String imageUrl = File.separator + myConfig.getVitrPath() + File.separator + "cms" + File.separator + TimeUtils.getTime() + suffixName;
        String imageUrl = "/" + myConfig.getVitrPath() + "/" + "cms" + "/" + tmppath;
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);

//            String config = "{\"state\": \"SUCCESS\"," +
//                    "\"url\":\"" + imageUrl + "\"," +
//                    "\"title\": \"" + fileName + "\"," +
//                    "\"original\": \"" + fileName + "\"}";
            //这个url是前台回显路径（回显路径为config.json中的imageUrlPrefix+此处的url）
            map.put("url", imageUrl);
            map.put("state", "SUCCESS");
            map.put("original", "===");
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /***
     * 判断文件路径是否存在，不存在创建一个新的路径
     * @param basePath 基础路径
     * @param tmpPath 不同的文件子路径
     *  @return 文件的绝对路径
     */
    private String pathIsExists(String basePath, String tmpPath) {
        File dir = new File(basePath + File.separator + tmpPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir.getAbsolutePath();
    }

    /**
     * 获取文件后缀
     *
     * @param file
     * @return 文件后缀
     */
    private String getFileSuffix(MultipartFile file) {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        return suffix;
    }
}
